import { SFValueChange } from '@delon/form';
import { Observable, Subject } from 'rxjs';

import { isObjectValueEqual } from './object';

/**
 * SF表单值变更事件监听，主要用于判定值是否有变化，及变更后，判断数值是否实际更新
 */
export class SFValueChangeHolder {
  private _changes = new Subject<any>();

  private _value?: SFValueChange;

  private _changeKey?: string;

  get value(): SFValueChange | undefined {
    return this._value;
  }

  get changes(): Observable<SFValueChange> {
    return this._changes.asObservable();
  }

  // 如果有变动，则触发变动
  changed(): void {
    this._changes.next(this.value);
  }

  /**
   * 初始化表单变更检测的值
   */
  reset(): void {
    this._value = undefined;
    this._changeKey = undefined;
  }

  // 表单值变动后，判定是否可以触发变动
  setValue(event: SFValueChange): void {
    if (this.value && isObjectValueEqual(this.value.value, event.value)) {
      // 如果相等则不触发变更事件
    } else if (event && this._changeKey && event.path !== this._changeKey) {
      this._changeKey = undefined;
    } else {
      this._changeKey = event.path!;
      this._value = event;
      this.changed();
    }
  }
}
